package com.rzcode.coinex.chain.event;

import com.alibaba.fastjson.JSON;
import com.rzcode.coinex.rpc.common.entity.Deposit;
import com.rzcode.coinex.rpc.common.service.DepositService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@AllArgsConstructor
public class DepositEvent {
    @Autowired
    private final DepositService depositService;
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;
    @Value("${coin.name}")
    private String coinName;

    public synchronized void onConfirmed(Deposit deposit) {
        log.info("confirmed deposit {}", JSON.toJSON(deposit));
        if (!depositService.exists(deposit)) {
            depositService.save(deposit);
            kafkaTemplate.send("deposit", coinName, JSON.toJSONString(deposit));
        }
    }
}
